package cn.deepmax.spring.cloud.system.product.controller;

import cn.deepmax.spring.cloud.common.web.AjaxResponse;
import cn.deepmax.spring.cloud.system.product.entity.Product;
import cn.deepmax.spring.cloud.system.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    ProductService productService;


    @GetMapping("index.json")
    public AjaxResponse index(){
        return AjaxResponse.ok("healthy.");
    }


    @GetMapping("/{id}.json")
    public AjaxResponse getProduct(HttpServletRequest request, @PathVariable(name = "id") Long id){
        log.info("Get request from {} , productId = {}.", request.getSession().getId(), id);
        Optional<Product> product = productService.findProduct(id);
        if(product.isPresent())
            return AjaxResponse.ok(product.get());
        else
            return AjaxResponse.fail("product not found");
    }




    @GetMapping("/list.json")
    public AjaxResponse productList(String name, @RequestParam(required = false, defaultValue = "0") Integer page,
                                  @RequestParam(required = false, defaultValue = "10") Integer size){
        Page<Product> productList = productService.findProductList(name, page, size);
        return AjaxResponse.ok(productList);

    }


}
